
#pragma once
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <iostream>
#include <string>

const std::string g_pathName = "./fifo";
const int g_size = 1024;
const int g_mode_p = 0600; // 起始权限
const int g_defaultfd = -1;
const int g_openForWrite = O_WRONLY;
const int g_openForRead = O_RDONLY;

class Pipe
{
public:
    Pipe()
    {
        int n = mkfifo(g_pathName.c_str(), g_mode_p);
        if (n == -1)
        {
            std::cerr << "mkfifo fail" << std::endl;
            return;
        }
        std::cerr << "mkfifo success" << std::endl;
    }
    ~Pipe()
    {
        unlink(g_pathName.c_str());
        std::cout << "管道被销毁" << std::endl;
    }

    void OpenForWrite()
    {
        _fd = openPipe("Client", g_openForWrite);
    }

    void OpenForRead()
    {
        _fd = openPipe("Server", g_openForRead);
    }

    void Signal()
    {
        int code = 1;
        ::write(_fd,&code,sizeof(code));
    }

    int Wait()
    {
        int buffer = 0;
        int n = read(_fd,&buffer,sizeof(buffer));
        if(n == 0)
            return 0;
        else 
            return 1;
    }

private:
    int openPipe(std::string name, int flag)
    {
        umask(0);
        // 如果读端打开，写端还没打开，读端阻塞
        int fd = open(g_pathName.c_str(), flag);
        if (fd == -1)
        {
            std::cout << name << " open fail" << std::endl;
        }
        std::cout << name << " open success" << std::endl;
        return fd;
    }

private:
    int _fd;
};

Pipe mypipe;
